<?php
/**
 * Admin Product Management for JSON File
 * CRUD operations for products stored in data/products.json
 */
session_start();

// Simple hardcoded authentication
$admin_username = 'admin';
$admin_password = 'admin123';

// Handle login
if (isset($_POST['login'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if ($username === $admin_username && $password === $admin_password) {
        $_SESSION['json_admin_logged_in'] = true;
        header('Location: products_json.php');
        exit;
    } else {
        $login_error = 'Invalid username or password';
    }
}

// Check if logged in
$is_logged_in = isset($_SESSION['json_admin_logged_in']) && $_SESSION['json_admin_logged_in'] === true;

// Handle logout
if (isset($_GET['logout'])) {
    unset($_SESSION['json_admin_logged_in']);
    header('Location: products_json.php');
    exit;
}

// Require login for all operations except login page
if (!$is_logged_in && !isset($_POST['login'])) {
    // Show login form
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin Login - Product Management</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }
            .login-container {
                background: white;
                border-radius: 12px;
                box-shadow: 0 10px 40px rgba(0,0,0,0.2);
                padding: 3rem;
                max-width: 400px;
                width: 100%;
            }
            .login-header {
                text-align: center;
                margin-bottom: 2rem;
            }
            .login-header h1 {
                color: #2c3e50;
                margin-bottom: 0.5rem;
            }
            .login-header p {
                color: #7f8c8d;
            }
            .form-group {
                margin-bottom: 1.5rem;
            }
            .form-group label {
                display: block;
                margin-bottom: 0.5rem;
                color: #2c3e50;
                font-weight: 500;
            }
            .form-group input {
                width: 100%;
                padding: 0.75rem;
                border: 2px solid #ecf0f1;
                border-radius: 8px;
                font-size: 1rem;
                transition: border-color 0.3s;
            }
            .form-group input:focus {
                outline: none;
                border-color: #667eea;
            }
            .btn {
                width: 100%;
                padding: 0.75rem;
                background: #667eea;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 1rem;
                font-weight: 600;
                cursor: pointer;
                transition: background 0.3s;
            }
            .btn:hover {
                background: #5568d3;
            }
            .error {
                background: #fee;
                color: #c33;
                padding: 1rem;
                border-radius: 8px;
                margin-bottom: 1rem;
                border-left: 4px solid #c33;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <div class="login-header">
                <h1><i class="fas fa-lock"></i> Admin Login</h1>
                <p>Product Management System</p>
            </div>
            
            <?php if (isset($login_error)): ?>
                <div class="error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($login_error); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST">
                <div class="form-group">
                    <label for="username"><i class="fas fa-user"></i> Username</label>
                    <input type="text" id="username" name="username" required autofocus>
                </div>
                
                <div class="form-group">
                    <label for="password"><i class="fas fa-key"></i> Password</label>
                    <input type="password" id="password" name="password" required>
                </div>
                
                <button type="submit" name="login" class="btn">
                    <i class="fas fa-sign-in-alt"></i> Login
                </button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Define JSON file path
$products_json_path = __DIR__ . '/../data/products.json';

// Load products
function loadProducts($file_path) {
    if (!file_exists($file_path)) {
        return [];
    }
    $content = file_get_contents($file_path);
    return json_decode($content, true) ?? [];
}

// Save products
function saveProducts($file_path, $products) {
    // Ensure directory exists
    $dir = dirname($file_path);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    // Validate and sanitize data
    $sanitized = array_map(function($product) {
        return [
            'id' => (int)($product['id'] ?? 0),
            'name' => trim(strip_tags($product['name'] ?? '')),
            'category' => trim(strip_tags($product['category'] ?? '')),
            'price' => (float)($product['price'] ?? 0),
            'discount_price' => isset($product['discount_price']) && $product['discount_price'] !== '' ? (float)$product['discount_price'] : null,
            'discount_percentage' => (int)($product['discount_percentage'] ?? 0),
            'quantity' => (int)($product['quantity'] ?? 0),
            'description' => trim(strip_tags($product['description'] ?? '')),
            'image_url' => filter_var($product['image_url'] ?? '', FILTER_SANITIZE_URL),
            'image_link' => filter_var($product['image_link'] ?? '', FILTER_SANITIZE_URL),
            'supplier' => trim(strip_tags($product['supplier'] ?? '')),
            'origin_country' => trim(strip_tags($product['origin_country'] ?? '')),
            'spice_level' => trim(strip_tags($product['spice_level'] ?? ''))
        ];
    }, $products);
    
    $json = json_encode($sanitized, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    return file_put_contents($file_path, $json) !== false;
}

// Handle POST requests (Create, Update, Delete)
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $products = loadProducts($products_json_path);
    
    switch ($action) {
        case 'add':
            // Generate new ID
            $max_id = 0;
            foreach ($products as $p) {
                if (isset($p['id']) && $p['id'] > $max_id) {
                    $max_id = $p['id'];
                }
            }
            
            $new_product = [
                'id' => $max_id + 1,
                'name' => $_POST['name'] ?? '',
                'category' => $_POST['category'] ?? '',
                'price' => $_POST['price'] ?? 0,
                'discount_price' => !empty($_POST['discount_price']) ? $_POST['discount_price'] : null,
                'discount_percentage' => $_POST['discount_percentage'] ?? 0,
                'quantity' => $_POST['quantity'] ?? 0,
                'description' => $_POST['description'] ?? '',
                'image_url' => $_POST['image_url'] ?? '',
                'image_link' => $_POST['image_link'] ?? $_POST['image_url'] ?? '',
                'supplier' => $_POST['supplier'] ?? '',
                'origin_country' => $_POST['origin_country'] ?? '',
                'spice_level' => $_POST['spice_level'] ?? ''
            ];
            
            // Calculate discount percentage if not provided
            if ($new_product['discount_price'] && $new_product['discount_percentage'] == 0 && $new_product['price'] > 0) {
                $new_product['discount_percentage'] = round((($new_product['price'] - $new_product['discount_price']) / $new_product['price']) * 100);
            }
            
            $products[] = $new_product;
            
            if (saveProducts($products_json_path, $products)) {
                $message = 'Product added successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error saving product.';
                $message_type = 'error';
            }
            break;
            
        case 'update':
            $product_id = (int)($_POST['id'] ?? 0);
            $updated = false;
            
            foreach ($products as &$product) {
                if (isset($product['id']) && $product['id'] == $product_id) {
                    $product['name'] = $_POST['name'] ?? $product['name'];
                    $product['category'] = $_POST['category'] ?? $product['category'];
                    $product['price'] = $_POST['price'] ?? $product['price'];
                    $product['discount_price'] = !empty($_POST['discount_price']) ? $_POST['discount_price'] : null;
                    $product['discount_percentage'] = $_POST['discount_percentage'] ?? $product['discount_percentage'];
                    $product['quantity'] = $_POST['quantity'] ?? $product['quantity'];
                    $product['description'] = $_POST['description'] ?? $product['description'];
                    $product['image_url'] = $_POST['image_url'] ?? $product['image_url'];
                    $product['image_link'] = $_POST['image_link'] ?? $_POST['image_url'] ?? $product['image_link'];
                    $product['supplier'] = $_POST['supplier'] ?? $product['supplier'];
                    $product['origin_country'] = $_POST['origin_country'] ?? $product['origin_country'];
                    $product['spice_level'] = $_POST['spice_level'] ?? $product['spice_level'];
                    
                    // Calculate discount percentage if not provided
                    if ($product['discount_price'] && $product['discount_percentage'] == 0 && $product['price'] > 0) {
                        $product['discount_percentage'] = round((($product['price'] - $product['discount_price']) / $product['price']) * 100);
                    }
                    
                    $updated = true;
                    break;
                }
            }
            
            if ($updated && saveProducts($products_json_path, $products)) {
                $message = 'Product updated successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error updating product.';
                $message_type = 'error';
            }
            break;
            
        case 'delete':
            $product_id = (int)($_POST['id'] ?? 0);
            $products = array_filter($products, function($product) use ($product_id) {
                return !isset($product['id']) || $product['id'] != $product_id;
            });
            $products = array_values($products); // Reset keys
            
            if (saveProducts($products_json_path, $products)) {
                $message = 'Product deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error deleting product.';
                $message_type = 'error';
            }
            break;
    }
}

// Load current products
$products = loadProducts($products_json_path);

// Get product for editing
$edit_product = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    foreach ($products as $product) {
        if (isset($product['id']) && $product['id'] == $edit_id) {
            $edit_product = $product;
            break;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Management - Admin Panel</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: #f5f6fa;
            color: #2c3e50;
            line-height: 1.6;
        }
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .admin-header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .admin-header h1 {
            font-size: 1.5rem;
        }
        .admin-header-actions {
            display: flex;
            gap: 1rem;
        }
        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.3s;
        }
        .btn-primary {
            background: white;
            color: #667eea;
        }
        .btn-primary:hover {
            background: #f0f0f0;
        }
        .btn-secondary {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .btn-secondary:hover {
            background: rgba(255,255,255,0.3);
        }
        .container {
            max-width: 1400px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #ecf0f1;
        }
        .card-header h2 {
            color: #2c3e50;
        }
        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        .product-card {
            background: white;
            border: 1px solid #ecf0f1;
            border-radius: 8px;
            padding: 1.5rem;
            transition: all 0.3s;
        }
        .product-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .product-image-preview {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 1rem;
            background: #f8f9fa;
        }
        .product-name {
            font-size: 1.25rem;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }
        .product-meta {
            font-size: 0.9rem;
            color: #7f8c8d;
            margin-bottom: 1rem;
        }
        .product-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        .btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.85rem;
        }
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        .btn-danger:hover {
            background: #c0392b;
        }
        .btn-edit {
            background: #3498db;
            color: white;
        }
        .btn-edit:hover {
            background: #2980b9;
        }
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #2c3e50;
            font-weight: 500;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #ecf0f1;
            border-radius: 6px;
            font-size: 1rem;
            font-family: inherit;
            transition: border-color 0.3s;
        }
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            overflow-y: auto;
        }
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            max-width: 800px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #ecf0f1;
        }
        .modal-header h2 {
            color: #2c3e50;
        }
        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #7f8c8d;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .close-btn:hover {
            color: #2c3e50;
        }
        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
            .products-grid {
                grid-template-columns: 1fr;
            }
            .admin-header-content {
                flex-direction: column;
                gap: 1rem;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="admin-header">
        <div class="admin-header-content">
            <h1><i class="fas fa-box"></i> Product Management - JSON File</h1>
            <div class="admin-header-actions">
                <a href="../products/" target="_blank" class="btn btn-secondary">
                    <i class="fas fa-eye"></i> View Products
                </a>
                <a href="?logout=1" class="btn btn-secondary">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>
    </div>
    
    <div class="container">
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <div class="card">
            <div class="card-header">
                <h2>All Products (<?php echo count($products); ?>)</h2>
                <button onclick="showAddModal()" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add New Product
                </button>
            </div>
            
            <?php if (empty($products)): ?>
                <div style="text-align: center; padding: 3rem; color: #7f8c8d;">
                    <i class="fas fa-box" style="font-size: 3rem; margin-bottom: 1rem;"></i>
                    <p>No products found. Click "Add New Product" to create your first product.</p>
                </div>
            <?php else: ?>
                <div class="products-grid">
                    <?php foreach ($products as $product): ?>
                        <div class="product-card">
                            <?php if (!empty($product['image_url'])): ?>
                                <?php
                                    $preview = $product['image_url'];
                                    if ($preview && strpos($preview, 'http') !== 0 && strpos($preview, '/') !== 0) {
                                        $preview = '../assets/images/' . rawurlencode(basename($preview));
                                    }
                                ?>
                                <img src="<?php echo htmlspecialchars($preview); ?>" 
                                     alt="<?php echo htmlspecialchars($product['name']); ?>" 
                                     class="product-image-preview"
                                     onerror="this.src='https://via.placeholder.com/400x200?text=No+Image'">
                            <?php else: ?>
                                <div class="product-image-preview" style="display: flex; align-items: center; justify-content: center; background: #ecf0f1;">
                                    <i class="fas fa-image" style="font-size: 3rem; color: #bdc3c7;"></i>
                                </div>
                            <?php endif; ?>
                            
                            <div class="product-name"><?php echo htmlspecialchars($product['name']); ?></div>
                            <div class="product-meta">
                                <div><strong>Category:</strong> <?php echo htmlspecialchars($product['category'] ?? 'N/A'); ?></div>
                                <div><strong>Price:</strong> $<?php echo number_format($product['price'] ?? 0, 2); ?></div>
                                <?php if (!empty($product['discount_price'])): ?>
                                    <div><strong>Discount:</strong> <span style="color: #e74c3c;">$<?php echo number_format($product['discount_price'], 2); ?> (<?php echo $product['discount_percentage'] ?? 0; ?>%)</span></div>
                                <?php endif; ?>
                                <div><strong>Quantity:</strong> <?php echo $product['quantity'] ?? 0; ?></div>
                                <div><strong>Supplier:</strong> <?php echo htmlspecialchars($product['supplier'] ?? 'N/A'); ?></div>
                            </div>
                            
                            <div class="product-actions">
                                <a href="?edit=<?php echo $product['id']; ?>" class="btn btn-edit btn-sm">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <button onclick="confirmDelete(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars(addslashes($product['name'])); ?>')" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Add/Edit Product Modal -->
    <div id="productModal" class="modal <?php echo $edit_product ? 'active' : ''; ?>">
        <div class="modal-content">
            <div class="modal-header">
                <h2><?php echo $edit_product ? 'Edit Product' : 'Add New Product'; ?></h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            
            <form method="POST" id="productForm">
                <input type="hidden" name="action" value="<?php echo $edit_product ? 'update' : 'add'; ?>">
                <?php if ($edit_product): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_product['id']; ?>">
                <?php endif; ?>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label for="name">Product Name *</label>
                        <input type="text" id="name" name="name" required 
                               value="<?php echo htmlspecialchars($edit_product['name'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="category">Category *</label>
                        <select id="category" name="category" required>
                            <option value="">Select Category</option>
                            <option value="Eau de Parfum" <?php echo ($edit_product['category'] ?? '') === 'Eau de Parfum' ? 'selected' : ''; ?>>Eau de Parfum</option>
                            <option value="Home Fragrance" <?php echo ($edit_product['category'] ?? '') === 'Home Fragrance' ? 'selected' : ''; ?>>Home Fragrance</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="price">Price ($) *</label>
                        <input type="number" id="price" name="price" step="0.01" min="0" required 
                               value="<?php echo $edit_product['price'] ?? ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="discount_price">Discount Price ($) (optional)</label>
                        <input type="number" id="discount_price" name="discount_price" step="0.01" min="0" 
                               value="<?php echo $edit_product['discount_price'] ?? ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="discount_percentage">Discount Percentage (%)</label>
                        <input type="number" id="discount_percentage" name="discount_percentage" min="0" max="100" 
                               value="<?php echo $edit_product['discount_percentage'] ?? 0; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="quantity">Quantity *</label>
                        <input type="number" id="quantity" name="quantity" min="0" required 
                               value="<?php echo $edit_product['quantity'] ?? ''; ?>">
                    </div>
                    
                    <div class="form-group full-width">
                        <label for="description">Description *</label>
                        <textarea id="description" name="description" required><?php echo htmlspecialchars($edit_product['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group full-width">
                        <label for="image_url">Image URL *</label>
                        <input type="url" id="image_url" name="image_url" required 
                               value="<?php echo htmlspecialchars($edit_product['image_url'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group full-width">
                        <label for="image_link">Image Link (optional)</label>
                        <input type="url" id="image_link" name="image_link" 
                               value="<?php echo htmlspecialchars($edit_product['image_link'] ?? $edit_product['image_url'] ?? ''); ?>">
                        <small style="color: #7f8c8d;">Leave empty to use Image URL</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="supplier">Supplier *</label>
                        <input type="text" id="supplier" name="supplier" required 
                               value="<?php echo htmlspecialchars($edit_product['supplier'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="origin_country">Origin Country *</label>
                        <input type="text" id="origin_country" name="origin_country" required 
                               value="<?php echo htmlspecialchars($edit_product['origin_country'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="spice_level">Intensity *</label>
                        <select id="spice_level" name="spice_level" required>
                            <option value="">Select Intensity</option>
                            <option value="None" <?php echo ($edit_product['spice_level'] ?? '') === 'None' ? 'selected' : ''; ?>>None</option>
                            <option value="Light" <?php echo ($edit_product['spice_level'] ?? '') === 'Light' ? 'selected' : ''; ?>>Light</option>
                            <option value="Medium" <?php echo ($edit_product['spice_level'] ?? '') === 'Medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="High" <?php echo ($edit_product['spice_level'] ?? '') === 'High' ? 'selected' : ''; ?>>High</option>
                        </select>
                    </div>
                </div>
                
                <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                    <button type="submit" class="btn btn-primary" style="flex: 1;">
                        <i class="fas fa-save"></i> <?php echo $edit_product ? 'Update Product' : 'Add Product'; ?>
                    </button>
                    <button type="button" onclick="closeModal()" class="btn btn-secondary" style="flex: 1;">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h2>Confirm Delete</h2>
                <button class="close-btn" onclick="closeDeleteModal()">&times;</button>
            </div>
            <p style="margin-bottom: 2rem;">Are you sure you want to delete "<strong id="deleteProductName"></strong>"? This action cannot be undone.</p>
            <form id="deleteForm" method="POST">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" id="deleteProductId">
                <div style="display: flex; gap: 1rem;">
                    <button type="submit" class="btn btn-danger" style="flex: 1;">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                    <button type="button" onclick="closeDeleteModal()" class="btn btn-secondary" style="flex: 1;">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function showAddModal() {
            window.location.href = 'products_json.php';
        }
        
        function closeModal() {
            window.location.href = 'products_json.php';
        }
        
        function confirmDelete(id, name) {
            document.getElementById('deleteProductId').value = id;
            document.getElementById('deleteProductName').textContent = name;
            document.getElementById('deleteModal').classList.add('active');
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('active');
        }
        
        // Close modal on outside click
        document.getElementById('productModal')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
        
        document.getElementById('deleteModal')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeleteModal();
            }
        });
        
        // Auto-calculate discount percentage
        document.getElementById('price')?.addEventListener('input', calculateDiscount);
        document.getElementById('discount_price')?.addEventListener('input', calculateDiscount);
        
        function calculateDiscount() {
            const price = parseFloat(document.getElementById('price')?.value) || 0;
            const discountPrice = parseFloat(document.getElementById('discount_price')?.value) || 0;
            
            if (price > 0 && discountPrice > 0 && discountPrice < price) {
                const percentage = Math.round(((price - discountPrice) / price) * 100);
                document.getElementById('discount_percentage').value = percentage;
            } else if (discountPrice === 0 || discountPrice >= price) {
                document.getElementById('discount_percentage').value = 0;
            }
        }
    </script>
</body>
</html>
